<script setup>
import request from "@/utils/request";
import { ref } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const form = ref({
    password: '',
    newPass: '',
    confirmPass: ''
});

const rules = {
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ],
    newPass: [
        { required: true, message: '请输入新密码', trigger: 'blur' }
    ],
    confirmPass: [
        { required: true, message: '请输入确认新密码', trigger: 'blur' }
    ]
};

const changePsss = () => {
    const validate = () => {
        const fields = Object.keys(rules);
        for (const field of fields) {
            const fieldRules = rules[field];
            for (const rule of fieldRules) {
                if (rule.required &&!form.value[field]) {
                    // 假设 $message 是通过 app.config.globalProperties.$message 挂载的全局方法
                    app.config.globalProperties.$message({
                        type: 'error',
                        message: rule.message
                    });
                    return false;
                }
            }
        }
        return true;
    };
    if (validate()) {
        if (form.value.newPass!== form.value.confirmPass) {
            app.config.globalProperties.$message({
                type: 'error',
                message: '2次输入新密码必须一致'
            });
            return;
        }
        const user = JSON.parse(sessionStorage.getItem("user"));
        form.value.userId = user.id;
        request.put("/user/pass", form.value).then(res => {
            if (res.code === '0') {
                app.config.globalProperties.$message({
                    type:'success',
                    message: '修改成功'
                });
                router.push("/login");
            } else {
                app.config.globalProperties.$message({
                    type: 'error',
                    message: res.msg
                });
            }
        });
    }
};
</script>

<template>
  <div>
    <el-card style="width: 40%; margin: 10px">
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="原密码" prop="password">
          <el-input v-model="form.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPass">
          <el-input v-model="form.newPass" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPass">
          <el-input v-model="form.confirmPass" show-password></el-input>
        </el-form-item>
      </el-form>

      <div style="text-align: center">
        <el-button type="primary" @click="changePsss">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<style scoped></style>
